﻿using Aop.Api;
using Aop.Api.Domain;
using Aop.Api.Request;
using Aop.Api.Response;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Writers;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using WCS.Api.Admin.AlipayPayment;
using WCS.Infrastructure.Attr;
using WCS.Infrastructure.Dto.Request.User;
using WCS.Infrastructure.Dto.Response;
using WCS.Infrastructure.Tools;
using WCS.Service.Instance;
using WCS.Service.Interface;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace WCS.Api.Admin.Controllers
{
    /// <summary>
    /// 用户管理
    /// </summary>
    public class UserController : BaseController
    {
        private readonly IConfiguration _configuration;
        public UserController(IUserService userService, IConfiguration configuration) : base(userService)
        {
            _configuration = configuration;
        }

        /// <summary>
        /// B端用户登录【phone,password】
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionLog(Action = "B端用户登录", Group = "登录模块")]
        [AllowAnonymous]
        public async Task<IActionResult> LoginWeChatToB(LoginRequestDto dto)
        {
            var result = await _userService.LoginWeChatToBAsync(dto);
            if (result.code == 0)
            {
                var claims = new[]
                {
                    new Claim(ClaimTypes.Name, result.data.ToString()),
                    new Claim(ClaimTypes.Role,"admin")
                };

                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:SecurityKey"]));
                var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
                string jwtKey = _configuration["JWT:issuer"];
                var token = new JwtSecurityToken(
                 issuer: jwtKey,
                 audience: jwtKey,
                 claims: claims,
                 expires: DateTime.Now.AddDays(30),//AddMinutes(60 * 12),
                 signingCredentials: creds);
                result.data = new JwtSecurityTokenHandler().WriteToken(token);
            }
            return Ok(result);
        }

        /// <summary>
        /// B端用户验证码登录【phone,VerificationCode】
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionLog(Action = "B端用户验证码登录", Group = "登录模块")]
        [AllowAnonymous]
        public async Task<IActionResult> LoginVerificationCodeToB(LoginRequestDto dto)
        {
            var result = await _userService.LoginVerificationCodeToBAsync(dto);
            if (result.code == 0)
            {
                var claims = new[]
                {
                    new Claim(ClaimTypes.Name, result.data.ToString()),
                    new Claim(ClaimTypes.Role,"admin")
                };

                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:SecurityKey"]));
                var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
                string jwtKey = _configuration["JWT:issuer"];
                var token = new JwtSecurityToken(
                 issuer: jwtKey,
                 audience: jwtKey,
                 claims: claims,
                 expires: DateTime.Now.AddDays(30),//AddMinutes(60 * 12),
                 signingCredentials: creds);
                result.data = new JwtSecurityTokenHandler().WriteToken(token);
            }
            return Ok(result);
        }

        /// <summary>
        /// 【废弃】C端用户微信登录（旺财神到家）【code】
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionLog(Action = "C端用户微信登录（旺财神到家）", Group = "登录模块")]
        [AllowAnonymous]
        public async Task<IActionResult> LoginWeChatToC(LoginRequestDto dto)
        {
            string appid = "wx104d55fcf708181b"; 
            string secret = "3d00242951ad229d832a0cd84c01db1c"; 
            string js_code = dto.code;
            string grant_type = "authorization_code";

            string wxResult = WCS.Infrastructure.Tools.Http.HttpGetNew("https://api.weixin.qq.com/sns/jscode2session" + $"?appid={appid}&secret={secret}&js_code={js_code}&grant_type={grant_type}");

            var wxResultJson = Newtonsoft.Json.JsonConvert.DeserializeObject<LoginRequestDto>(wxResult);

            if (wxResultJson.errcode != null)
            {
                return Ok(new
                {
                    code = wxResultJson.errcode,
                    message = wxResultJson.errmsg
                });
            }

            dto.openid = wxResultJson.openid;
            dto.unionid = wxResultJson.unionid;
            dto.appid = appid;

            var result = await _userService.LoginWeChatToCAsync(dto);
            if (result.code == 0)
            {
                var claims = new[]
                {
                    new Claim(ClaimTypes.Name, result.data.ToString()),
                    new Claim(ClaimTypes.Role,"admin")
                };

                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:SecurityKey"]));
                var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
                string jwtKey = _configuration["JWT:issuer"];
                var token = new JwtSecurityToken(
                 issuer: jwtKey,
                 audience: jwtKey,
                 claims: claims,
                 expires: DateTime.Now.AddDays(30),//AddMinutes(60 * 12),
                 signingCredentials: creds);
                result.data = new JwtSecurityTokenHandler().WriteToken(token);
            }
            return Ok(result);
        }

        /// <summary>
        /// C端用户微信登录（AI奇遇）【code】
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionLog(Action = "C端用户微信登录（AI奇遇）", Group = "登录模块")]
        [AllowAnonymous]
        public async Task<IActionResult> LoginWeChatToCAi(LoginRequestDto dto)
        {
            string appid = "wx70b4fba4a35c8fa0"; //AI奇遇：wx70b4fba4a35c8fa0//元秘境：wx927712aed4a98e7e
            string secret = "5561c798f7275c38390ef53343f73312";//AI奇遇：5561c798f7275c38390ef53343f73312//元秘境：08e97169b4263bf07d2dff40a55b6025
            string js_code = dto.code;
            string grant_type = "authorization_code";

            string wxResult = WCS.Infrastructure.Tools.Http.HttpGetNew("https://api.weixin.qq.com/sns/jscode2session" + $"?appid={appid}&secret={secret}&js_code={js_code}&grant_type={grant_type}");

            var wxResultJson = Newtonsoft.Json.JsonConvert.DeserializeObject<LoginRequestDto>(wxResult);

            if (wxResultJson.errcode != null)
            {
                return Ok(new
                {
                    code = wxResultJson.errcode,
                    message = wxResultJson.errmsg
                });
            }

            dto.openid = wxResultJson.openid;
            dto.unionid = wxResultJson.unionid;
            dto.appid = appid;

            var result = await _userService.LoginWeChatToCAsync(dto);
            if (result.code == 0)
            {
                var claims = new[]
                {
                    new Claim(ClaimTypes.Name, result.data.ToString()),
                    new Claim(ClaimTypes.Role,"admin")
                };

                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:SecurityKey"]));
                var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
                string jwtKey = _configuration["JWT:issuer"];
                var token = new JwtSecurityToken(
                 issuer: jwtKey,
                 audience: jwtKey,
                 claims: claims,
                 expires: DateTime.Now.AddDays(30),//AddMinutes(60 * 12),
                 signingCredentials: creds);
                result.data = new JwtSecurityTokenHandler().WriteToken(token);
            }
            return Ok(result);
        }

        /// <summary>
        /// C端用户微信登录（元秘境）【code】
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionLog(Action = "C端用户微信登录（元秘境）", Group = "登录模块")]
        [AllowAnonymous]
        public async Task<IActionResult> LoginWeChatToCYuan(LoginRequestDto dto)
        {
            string appid = "wx927712aed4a98e7e"; //AI奇遇：wx70b4fba4a35c8fa0//元秘境：wx927712aed4a98e7e
            string secret = "08e97169b4263bf07d2dff40a55b6025";//AI奇遇：5561c798f7275c38390ef53343f73312//元秘境：08e97169b4263bf07d2dff40a55b6025
            string js_code = dto.code;
            string grant_type = "authorization_code";

            string wxResult = WCS.Infrastructure.Tools.Http.HttpGetNew("https://api.weixin.qq.com/sns/jscode2session" + $"?appid={appid}&secret={secret}&js_code={js_code}&grant_type={grant_type}");

            var wxResultJson = Newtonsoft.Json.JsonConvert.DeserializeObject<LoginRequestDto>(wxResult);

            if (wxResultJson.errcode != null)
            {
                return Ok(new
                {
                    code = wxResultJson.errcode,
                    message = wxResultJson.errmsg
                });
            }

            dto.openid = wxResultJson.openid;
            dto.unionid = wxResultJson.unionid;
            dto.appid = appid;

            var result = await _userService.LoginWeChatToCAsync(dto);
            if (result.code == 0)
            {
                var claims = new[]
                {
                    new Claim(ClaimTypes.Name, result.data.ToString()),
                    new Claim(ClaimTypes.Role,"admin")
                };

                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:SecurityKey"]));
                var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
                string jwtKey = _configuration["JWT:issuer"];
                var token = new JwtSecurityToken(
                 issuer: jwtKey,
                 audience: jwtKey,
                 claims: claims,
                 expires: DateTime.Now.AddDays(30),//AddMinutes(60 * 12),
                 signingCredentials: creds);
                result.data = new JwtSecurityTokenHandler().WriteToken(token);
            }
            return Ok(result);
        }

        /// <summary>
        /// C端用户微信登录（公众号，惠旺店会员端）【code】
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionLog(Action = "C端用户微信登录（公众号）", Group = "登录模块")]
        [AllowAnonymous]
        public async Task<IActionResult> LoginWeChatToCJS(LoginRequestDto dto)
        {
            string appid = "wxf996db986e976eb7";
            string secret = "bb8a34937bb1d1f69ae9f8e4bf649f60";
            string js_code = dto.code;
            string grant_type = "authorization_code";

            string wxResult = WCS.Infrastructure.Tools.Http.HttpGetNew("https://api.weixin.qq.com/sns/oauth2/access_token" + $"?appid={appid}&secret={secret}&code={js_code}&grant_type={grant_type}");
         
            var wxResultJson = Newtonsoft.Json.JsonConvert.DeserializeObject<LoginRequestDto>(wxResult);

            //string wxResult1 = WCS.Infrastructure.Tools.Http.HttpGetNew($"https://api.weixin.qq.com/sns/userinfo?access_token={wxResultJson.access_token}&openid={wxResultJson.openid}&lang=zh_CN");
            //var wxResultJson1 = Newtonsoft.Json.JsonConvert.DeserializeObject<LoginRequestDto>(wxResult1);

            if (wxResultJson.errcode != null)
            {
                return Ok(new
                {
                    code = wxResultJson.errcode,
                    message = wxResultJson.errmsg
                });
            }

            dto.openid = wxResultJson.openid;
            dto.unionid = wxResultJson.unionid;
            dto.appid = appid;

            var result = await _userService.LoginWeChatToCAsync(dto);
            if (result.code == 0)
            {
                var claims = new[]
                {
                    new Claim(ClaimTypes.Name, result.data.ToString()),
                    new Claim(ClaimTypes.Role,"admin")
                };

                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:SecurityKey"]));
                var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
                string jwtKey = _configuration["JWT:issuer"];
                var token = new JwtSecurityToken(
                 issuer: jwtKey,
                 audience: jwtKey,
                 claims: claims,
                 expires: DateTime.Now.AddDays(30),//AddMinutes(60 * 12),
                 signingCredentials: creds);
                result.data = new JwtSecurityTokenHandler().WriteToken(token);
            }
            return Ok(result);
        }

        /// <summary>
        /// C端用户支付宝登录【code】
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionLog(Action = "C端用户支付宝登录", Group = "登录模块")]
        [AllowAnonymous]
        public async Task<IActionResult> LoginAlipayPaymentToC(LoginRequestDto dto)
        {
            // 初始化SDK
            IAopClient alipayClient = new DefaultAopClient(AlipayUserInfoAuth.GetAlipayConfig());
            // 构造请求参数以调用接口
            AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();

            // 设置刷新令牌
            request.RefreshToken = "201208134b203fe6c11548bcabd8da5bb087a84b";

            // 设置授权码
            request.Code = dto.code;

            // 设置授权方式
            request.GrantType = "authorization_code";

            AlipaySystemOauthTokenResponse response = alipayClient.Execute(request);

            if (!response.IsError)
            {
                Console.WriteLine("调用成功");
            }
            else
            {
                Console.WriteLine("调用失败");
                return Ok(new
                {
                    message = "登录失败"
                });
            }

            dto.openid = response.OpenId;
            dto.userid = response.UserId;
            dto.appid = AlipayUserInfoAuth.GetAlipayConfig().AppId;

            var result = await _userService.LoginAlipayPaymentToCAsync(dto);
            if (result.code == 0)
            {
                var claims = new[]
                {
                    new Claim(ClaimTypes.Name, result.data.ToString()),
                    new Claim(ClaimTypes.Role,"admin")
                };

                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:SecurityKey"]));
                var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
                string jwtKey = _configuration["JWT:issuer"];
                var token = new JwtSecurityToken(
                 issuer: jwtKey,
                 audience: jwtKey,
                 claims: claims,
                 expires: DateTime.Now.AddDays(30),//AddMinutes(60 * 12),
                 signingCredentials: creds);
                result.data = new JwtSecurityTokenHandler().WriteToken(token);
            }
            return Ok(result);
        }

        /// <summary>
        /// 获取当前用户的虚拟账信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetUserVirtualAccount()
        {
            var result = await _userService.GetUserVirtualAccountAsync();
            return Ok(result);
        }

        /// <summary>
        /// 获取当前登录用户信息,校验用户登录状态(获取失败代表用户登录过期，需要重新登录)
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ActionLog(Action = "获取当前登录用户信息", Group = "用户管理")]
        //[Authorize(Roles = "admin")]
        public async Task<IActionResult> GetUserByCode()
        {
            var code = Response.HttpContext.User.Identity?.Name;
            var result = await _userService.GetUserByCodeAsync(code);
            return Ok(result);
            //var result = await this.GetCurrentUser();
            //return Ok(result);
        }

        /// <summary>
        /// 获取按钮状态
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public string GetButtonState()
        {
            var isButton = _configuration["ButtonState"];
            return isButton;
        }
        
        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <param name="page">页数</param>
        /// <param name="limit">每页条数</param>
        /// <param name="key">查询条件【根据用户名】</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetUserList(int page = 1, int limit = 10, string? key = "")
        {
            var result = await _userService.GetUserListAsync(new UserRequestDto
            {
                Page = page,
                Limit = limit,
                Key = key,
            });

            return Ok(result);
        }

        /// <summary>
        /// 新增用户【name,phone,password】
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionLog(Action = "新增用户", Group = "用户管理")]
        [AllowAnonymous]
        public async Task<IActionResult> AddUser(UserRequestDto dto)
        {
            var result = await _userService.AddUserAsync(dto);
            return Ok(result);
        }

        /// <summary>
        /// 修改账户密码
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionLog(Action = "修改账户密码", Group = "用户管理")]
        [AllowAnonymous]
        public async Task<IActionResult> UpdateUserPassword(UserPasswordUpdateRequestDto dto)
        {
            var result = await _userService.UpdateUserPasswordAsync(dto);
            return Ok(result);
        }

        /// <summary>
        /// 修改用户头像
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionLog(Action = "修改用户头像", Group = "用户管理")]
        public async Task<IActionResult> UpdateUserAvatar(UserAvatarUpdateRequestDto dto)
        {
            var result = await _userService.UpdateUserAvatarAsync(dto);
            return Ok(result);
        }

        /// <summary>
        /// 实名用户信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> RealNameUserInformation(RealNameUserInformationRequestDto dto)
        {
            var result = await _userService.RealNameUserInformationAsync(dto);
            return Ok(result);
        }

        /// <summary>
        /// 校验实名用户信息
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> CheckRealNameUserInformation(string? userId)
        {
            var result = await _userService.CheckRealNameUserInformationAsync(userId);
            return Ok(result);
        }

        /// <summary>
        /// 删除用户【ids[]】
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionLog(Action = "删除用户", Group = "用户管理")]
        public async Task<IActionResult> DeleteUser(UserRequestDto dto)
        {
            var result = await _userService.DeleteUserAsync(dto);
            return Ok(result);
        }

        /// <summary>
        /// 禁用/启用 用户【ids[],EnableStatus】
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionLog(Action = "禁用/启用 用户", Group = "用户管理")]
        public async Task<IActionResult> BanUser(UserRequestDto dto)
        {
            var result = await _userService.BanUserAsync(dto);
            return Ok(result);
        }


        ///// <summary>
        ///// 检测用户是否登录
        ///// </summary>
        ///// <returns></returns>
        //[HttpGet]
        //public async Task<IActionResult> CheckLogins()
        //{
        //    var result = await this.GetCurrentUser();
        //    return Ok(result);
        //}

    }
}
